﻿using Chloe;
using Chloe.SqlServer;
using Chloe.MySql;
using System.Configuration;

namespace Aierp.Utility.Data
{
    public class DbContextFactory
    {
        public const string DefaultConnectionStringName = "DefaultConnection";
        public static string ConnectionString { get; private set; }
        public static string DbType { get; private set; }
        static DbContextFactory()
        {
            ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings[DefaultConnectionStringName];
            if (setting != null)
            {
                string connString = setting.ConnectionString;
                ConnectionString = connString;

            }

            string dbType = ConfigurationManager.AppSettings["DbType"];

            if (string.IsNullOrEmpty(dbType) == false)
                DbType = dbType.ToLower();
        }
        public static IDbContext CreateContext()
        {
            IDbContext dbContext = CreateContext(ConnectionString);
            return dbContext;
        }
        public static IDbContext CreateContext(string connString)
        {
            IDbContext dbContext = null;

            
            if (DbType == "sqlserver")
            {
                dbContext = CreateSqlServerContext(connString);
            }
            else if (DbType == "mysql")
            {
                dbContext = CreateMySqlContext(connString);
            }
            else
            {
                dbContext = CreateSqlServerContext(connString);
            }

            return dbContext;
        }

        static IDbContext CreateSqlServerContext(string connString)
        {
            MsSqlContext dbContext = new MsSqlContext(connString);
            //dbContext.PagingMode = PagingMode.OFFSET_FETCH;
            return dbContext;
        }
        static IDbContext CreateMySqlContext(string connString)
        {
            MySqlContext dbContext = new MySqlContext(new MySqlConnectionFactory(connString));
            return dbContext;
        }
    }
}
